# @Time : 2020/8/31 15:22
# @Author : Fioman 
# @Phone : 13149920693
import cv2 as cv
import imutils
from matplotlib import pyplot as plt

image = cv.imread("pic/27.png")
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

channels = cv.split(image)
colors = ("b", "g", "r")
plt.figure()
plt.title("Flatten")
plt.xlabel("Bins")
plt.ylabel("# of Pixels")

for (chan,color) in zip(channels,colors):
    hist = cv.calcHist([chan],[0],None,[256],[0,256])
    plt.plot(hist,color=color)
    plt.xlim([0,256])

fig = plt.figure()
ax = fig.add_subplot(131)
hist = cv.calcHist([channels[1],channels[0]],[0,1],None,[32,32],[0,256,0,256])
p = ax.imshow(hist,interpolation="nearest")
ax.set_title("2D Color Histogram For G and B")
plt.colorbar(p)

# plot a 2D color histogram for green and red
ax = fig.add_subplot(132)
hist = cv.calcHist([channels[1],channels[2]],[0,1],None,[32,32],[0,256,0,256])
p = ax.imshow(hist,interpolation="nearest")
ax.set_title("2D color Histogram for G and R")
plt.colorbar(p)


ax = fig.add_subplot(133)
hist = cv.calcHist([channels[0],channels[2]],[0,1],None,[32,32],[0,256,0,256])
p = ax.imshow(hist,interpolation="nearest")
ax.set_title("2D Color Histogram for B and R")
plt.colorbar(p)

print("2D histogram shape: {},with {} values".format(hist.shape,hist.flatten().shape[0]))


hist = cv.calcHist([image],[0,1,2],None,[8,8,8],[0,256,0,256,0,256])
print("3D histogram shape: {},with {} values".format(hist.shape,hist.flatten().shape[0]))

plt.figure()
plt.axis("off")
plt.imshow(imutils.opencv2matplotlib(image))
plt.show()